﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloudTree.Models;
using CloudTree.Domain;

namespace CloudTree.Controllers
{
    public class EmployeeController : Controller
    {
        private readonly IDepartmentDataSource _db;

        public EmployeeController(IDepartmentDataSource db)
        {
            _db = db;
        }
        //
        // GET: /Employee/
        [HttpGet]
        public ActionResult Create(int departmentId)
        {
            var model = new CreateEmployeeViewModel();
            model.DepartmentID = departmentId;
            return View(model);
        }


        [HttpPost]
        [ValidateAntiForgeryToken]//CSRF Attack - Anti-forgery token
        public ActionResult Create(CreateEmployeeViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var department = _db.Departments.Single(d => d.ID == viewModel.DepartmentID);
                var employee = new Employee();
                employee.Name = viewModel.Name;
                employee.HireDate = viewModel.HireDate;
                department.Employees.Add(employee);
                
                _db.Save();

                return RedirectToAction("detail","department", new{id = viewModel.DepartmentID});
            }
            return View(viewModel);
        }
    }
}
